//
//  WBRefreshControl.swift
//  weibo
//
//  Created by 陈伟 on 15/10/22.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit

class WBRefreshControl: UIRefreshControl {
    
    override func beginRefreshing() {
        super.beginRefreshing()
//        print("开始刷新了")
        refreshingView.startAnimation()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
//        print("刷完了")
        refreshingView.stopAnimation()
    }

    //监听frame的变化
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(frame)
        
        //向上Y > 0 
        if frame.origin.y > 0 {
            return
        }
        
        if frame.origin.y < -60 && refreshingView.totateFlag == false{
            refreshingView.totateFlag = true
        }
        
        if frame.origin.y > -60 && refreshingView.totateFlag == true{
            refreshingView.totateFlag = false
        }
    }
    
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI () {
        addSubview(refreshingView)
        refreshingView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshingView.bounds.size)
        }
        //主线程就不程序启动就开始监听
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    //删除KVO监听方法
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    private lazy var refreshingView = WBRefreshView.refreshingView()
}


//xib加载部分。主要处理动画
class WBRefreshView: UIView {
    //旋转标记
    var totateFlag = false {
        didSet {
//            print("标记变了")
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var loadImageView: UIImageView!
    @IBOutlet weak var refreshImageView: UIImageView!
    @IBOutlet weak var refreshView: WBRefreshView!
    
    class func refreshingView() -> WBRefreshView {
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).first as! WBRefreshView
    }
    
    private func rotateTipIcon() {
        UIView.animateWithDuration(0.5) { () -> Void in
            
            let offset = self.totateFlag ? -0.0000001 : 0.0000001
            self.refreshImageView.transform = CGAffineTransformRotate(self.refreshImageView.transform, CGFloat(M_PI + offset))
        }
    }
    
    private func startAnimation() {
//        print("开始动画")
        //隐藏顶部
        refreshView.hidden = true
        //如果loadImageView 有动画。。就不添加
        let key = "transform.rotation"
        if loadImageView.layer.animationForKey(key) != nil {
            return
        }
        
        //如果没有动画，添加一个动画效果
        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        
        loadImageView.layer.addAnimation(anim, forKey: key)
    }
    
    private func stopAnimation() {
//        print("结束动画")
        refreshView.hidden = false
        loadImageView.layer.removeAllAnimations()
    }
    
}
